//
//  MHLoginViewController.m
//  MiaoCircle
//
//  Created by acgera on 2018/4/10.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHLoginViewController.h"
#import "MHLoginViewModel.h"
#import "MHWebViewModel.h"
#import "MHH5Links.h"
#import "UITextView+Placeholder.h"
@interface MHLoginViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIButton *weChatLoginBtn;
@property(nonatomic,strong,readwrite) YYLabel *protocolLable;
@property(nonatomic,strong,readonly) MHLoginViewModel *viewModel;
@property (weak, nonatomic) IBOutlet UIButton *accoutLogin;
@property (nonatomic, strong) AVPlayer *player;
@end

@implementation MHLoginViewController
@dynamic viewModel;

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self masLayoutSubViews];
    [self setUpSubViews];
//    self.
    
    self.passworldFeild.delegate = self;
    self.weChatLoginBtn.titleLabel.font = MHRegularFont_18;
//    self.accountTextField.attributedPlaceholder = MHWhiteTextColor;
//    self.a.placeholderColor = MHWhiteTextColor;
    
    if ([self.accountTextField respondsToSelector:@selector(setAttributedPlaceholder:)]) {
        UIColor *color = [[UIColor whiteColor] colorWithAlphaComponent:0.5];
        self.accountTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入用户名" attributes:@{NSForegroundColorAttributeName: color}];
        self.passworldFeild.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入密码" attributes:@{NSForegroundColorAttributeName: color}];
    } else {
//        NSLog(@"Cannot set placeholder text's color, because deployment target is earlier than iOS 6.0");
        // TODO: Add fall-back code to set placeholder color.
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //播放视频
    [self.player play];
     self.navigationController.navigationBar.hidden  = YES;
    //注册通知，app从后台再次进入前台后继续播放视频
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoAgain) name:@"VideoAgain" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden  = NO;
}

-(void) setUpSubViews
{
    //可以打开微信就用微信;
//    self.viewModel.isInstallWechat =  [AXAppDelegate sharedDelegate].isAuthorizationExpired;
//    self.loginView.hidden = self.viewModel.isInstallWechat;
    
    [self.weChatLoginBtn setImage:[UIImage imageNamed:@"icon_loginbtn_bg"] forState:0];
//    if (self.viewModel.isInstallWechat) {
//        [self.weChatLoginBtn setImage:[UIImage imageNamed:@"icon_loginbtn_bg"] forState:0];
//        
//    }else{
//        [self.weChatLoginBtn setTitle:LSSTRING("登录") forState:0];
//        [self.weChatLoginBtn setImage:nil forState:0];
//        [self.weChatLoginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//        [self.weChatLoginBtn setBackgroundImage:[UIImage imageWithColor:MHColorFromHexString(@"#fe313d")] forState:0];
//    }
//    self.view.backgroundColor = [UIColor wheatColor];
}

- (void)videoAgain
{
    [self.player play];
}

-(void) masLayoutSubViews
{
    [self.protocolLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.weChatLoginBtn.mas_bottom).offset(40);
//        if (@available(iOS 11.0, *)) {
//            make.bottom.equalTo(self.mas_bottomLayoutGuide).with.offset(-MHGlobalBottomMarginHeight);
//        } else {
//            make.bottom.equalTo(self.view).with.offset(-MHGlobalBottomMarginHeight);
//        }
        make.centerX.equalTo(self.view);

    }];
}

- (IBAction)accountLogin:(id)sender {
    if (self.accountTextField.text.length <= 0 || self.passworldFeild.text.length <= 0) {
        [UIWindow showTips:@"请输入用户名或者密码"];
        return;
    }
    self.viewModel.password = self.passworldFeild.text;
    
    self.viewModel.account = self.accountTextField.text;
    [self.viewModel.accountLoginCommand execute:nil];
}

- (IBAction)weChatLoginAction:(UIButton *)sender {
    
    if (![OpenShare isWeixinInstalled]) {
        [MBProgressHUD mh_showTips:@"请先安装微信"];
        return;
    }
    sender.enabled = false;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        sender.enabled = YES;
    });
    [self.viewModel.weChatLoginCommand execute:nil];
}


-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

-(void)bindViewModel
{
    [super bindViewModel];
}
-(YYLabel *)protocolLable
{
    if(!_protocolLable)
    {
        _protocolLable = [YYLabel new];
        _protocolLable.textAlignment = NSTextAlignmentCenter;
        _protocolLable.textVerticalAlignment = YYTextVerticalAlignmentCenter;
        _protocolLable.numberOfLines = 0;
//        _protocolLable.backgroundColor = [UIColor colorWithWhite:0.933 alpha:1.000];
        NSMutableAttributedString *one = [[NSMutableAttributedString alloc] initWithString:LSSTRING("用户协议")];
        one.yy_font = MHMediumFont14;
//        one.yy_underlineStyle = NSUnderlineStyleSingle;
        [one yy_setTextHighlightRange:one.yy_rangeOfAll
                                color:MHMetionTextColor
                      backgroundColor:[UIColor clearColor]
                            tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
//                                [_self showMessage:[NSString stringWithFormat:@"Tap: %@",[text.string substringWithRange:range]]];
                            }];
        NSMutableAttributedString *text = [NSMutableAttributedString new];
        [text appendAttributedString:one];
        @weakify(self);
        _protocolLable.textTapAction = ^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
            YYCache *cache=[YYCache cacheWithName:MHCacheGlobleKey];
            @strongify(self);
             NSArray *h5Links  =  [cache objectForKey:MHH5LinksKey];
            for (MHH5Links *link in h5Links) {
                if ([link.type isEqualToString:@"yhxy"]) {
                    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:link.url]];
                    MHWebViewModel * webViewModel = [[MHWebViewModel alloc] initWithServices:self.viewModel.services params:@{MHViewModelRequestKey:request}];
                    [self.viewModel.services pushViewModel:webViewModel animated:YES];
                    return ;
                }
            }
            
        };
        //        [text appendAttributedString:[self padding]];
        [self.view addSubview:_protocolLable];
        _protocolLable.attributedText = text;
    }
    return _protocolLable;
}

- (AVPlayer *)player
{
    if (!_player) {
        
        //获取本地视频文件路径
        NSString *path = [[NSBundle mainBundle]pathForResource:@"loginvideo.mp4" ofType:nil];
        
        NSURL *url = [NSURL fileURLWithPath:path];
        
        //创建一个播放的item
        AVPlayerItem *playItem = [AVPlayerItem playerItemWithURL:url];
        
        //播放设置
        _player = [AVPlayer playerWithPlayerItem:playItem];
        //永不暂停
        _player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
        
        //设置播放器
        AVPlayerLayer *layerPlay = [AVPlayerLayer playerLayerWithPlayer:_player];
        layerPlay.frame = self.view.frame;
        layerPlay.videoGravity=AVLayerVideoGravityResizeAspectFill;
        // 将播放器至于底层，不然UI部分会被视频遮挡
        [self.view.layer insertSublayer:layerPlay atIndex:0];
        //设置通知，视频播放结束后 从头再次播放，达到循环的效果
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playAgain) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
        
    }
    return _player;
}

- (void)playAgain
{
    // 重头再来 seekToTime跳转到相应的时间播放
    [self.player seekToTime:kCMTimeZero];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
